<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="合同编号" prop="contractNo">
        <el-input
          v-model="queryParams.contractNo"
          placeholder="请输入合同编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="老人姓名" prop="elderName">
        <el-input
          v-model="queryParams.elderName"
          placeholder="请输入老人姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker clearable
          v-model="queryParams.startTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker clearable
          v-model="queryParams.endTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>
	  <el-form-item label="合同状态" prop="status">
	    <el-select
	      v-model="queryParams.status"
	      placeholder="请选择合同状态"
	      clearable
		  style="width: 195px;"
	      @change="handleQuery"
	    >
	      <el-option label="未生效" value="0"></el-option>
	      <el-option label="已生效" value="1"></el-option>
	      <el-option label="已过期" value="2"></el-option>
	      <el-option label="已失效" value="3"></el-option>
	    </el-select>
	  </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    

    <el-table v-loading="loading" :data="contractList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" align="left" prop="id" width="80"/>
      <el-table-column label="合同编号" align="left" prop="contractNo" />
      <el-table-column label="合同名称" align="left" prop="contractName" width="160"/>
      <el-table-column label="老人姓名" align="left" prop="elderName" />
	  <el-table-column label="老人身份证号" align="left" prop="elderIdCard" width="200">
	    <template #default="scope">
	      <!-- 为单元格内容添加不换行样式 -->
	      <span style="white-space: nowrap;">{{ scope.row.elderIdCard }}</span>
	    </template>
	  </el-table-column>
      <el-table-column label="合同期限" align="left" width="250">
        <template #default="scope">
          <span>
            {{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }} —— {{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="合同状态" align="left">
        <template #default="scope">
          <!-- 用el-tag渲染状态，通过方法动态控制类型和文字 -->
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="left" prop="createdBy" />
      <el-table-column label="创建时间" align="left" prop="createdAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
        <template #default="scope">
		  <el-button link type="primary" v-hasPermi="['residing:contract:edit']" @click="handleViewDetail(scope.row.id)">查看</el-button>
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['residing:contract:edit']">修改</el-button> -->
          <!-- <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['residing:contract:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改合同跟踪对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="contractRef" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Contract">
import { listContract, getContract, delContract, addContract, updateContract } from "@/api/residing/contract"

const { proxy } = getCurrentInstance()

const contractList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    contractNo: null,
    elderName: null,
    startTime: null,
    endTime: null,
    status: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询合同跟踪列表 */
function getList() {
  loading.value = true
  listContract(queryParams.value).then(response => {
    contractList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    contractNo: null,
    contractName: null,
    elderName: null,
    elderIdCard: null,
    startTime: null,
    endTime: null,
    status: null,
    createdBy: null,
    createdAt: null,
    agreementUrl: null,
    partyCPhone: null,
    elderId: null,
    partyCName: null,
    sortOrder: null,
    levelDesc: null,
    updatedAt: null,
    updatedBy: null,
    checkinNo: null,
    signDate: null,
    terminateBy: null,
    terminateDate: null,
    terminateAgreementUrl: null,
    checkoutId: null,
    remark: null,
    extend2: null
  }
  proxy.resetForm("contractRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加合同跟踪"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getContract(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改合同跟踪"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["contractRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateContract(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addContract(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除合同跟踪编号为"' + _ids + '"的数据项？').then(function() {
    return delContract(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('residing/contract/export', {
    ...queryParams.value
  }, `contract_${new Date().getTime()}.xlsx`)
}

getList()

const getStatusTagType = (status) => {
  switch (status) {
    case '0':
      return "info";    // 未生效，可选 info/primary/success/warning/danger 等
    case '1':
      return "success"; // 已生效（绿色标签）
    case '2':
      return "warning"; // 已过期（橙色标签）
    case '3':
      return "danger";  // 已失效（红色标签）
    default:
      return "";
  }
};

// 方法2：状态值 → 显示文字
const getStatusText = (status) => {
  switch (status) {
    case '0':
      return "未生效";
    case '1':
      return "生效中";
    case '2':
      return "已过期";
    case '3':
      return "已失效";
    default:
      return "未知状态";
  }
};

const router = useRouter()

// 点击查看，跳转到详情页并传递合同ID
const handleViewDetail = (id) => {
  router.push({
    name: 'ContractDetail', // 对应路由配置中的name
    params: { id } // 传递合同ID参数
  })
}




</script>
